<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 95%;overflow-y: hidden">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色名称">
          <a-input placeholder="请输入角色名称" v-decorator="[ 'roleName', validatorRules.roleName]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色编码">
          <a-input placeholder="请输入角色编码" v-decorator="[ 'roleCode', validatorRules.roleCode]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色描述">
          <a-textarea :rows="5" placeholder="..." v-decorator="[ 'roleDesc', validatorRules.roleDesc ]"/>
        </a-form-item>

        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="数据权限">
          <a-select placeholder="请选择数据权限" @change="handleChange" v-decorator="[ 'dsType', validatorRules.dsType ]">
            <a-select-option v-for="item in dateScopes" :key="item.id">{{item.des}}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="dsType == 4" label="数据权限" hasFeedback>
          <a-tree-select
            style="width:100%"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            :value="deptIds"
            treeCheckable
            @change="onChange"
            :showCheckedStrategy="SHOW_PARENT"
            placeholder="请选择数据权限">
          </a-tree-select>
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import { addRole, updateRole } from '@/api/role'
  import { queryDepartTreeList } from '@/api/dept'
  import { TreeSelect } from 'ant-design-vue'
  const SHOW_PARENT = TreeSelect.SHOW_ALL

  export default {
    name: 'RoleModal',
    data () {
      return {
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          roleName: {
            rules: [
              { required: true, message: '请输入角色名称!' },
              { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
            ]
          },
          roleCode: {
            rules: [
              { required: true, message: '请输入角色名称!' },
              { min: 0, max: 64, message: '长度不超过 64 个字符', trigger: 'blur' }
              // { validator: this.validateRoleCode }
            ]
          },
          roleDesc: {
            rules: [
              { min: 0, max: 126, message: '长度不超过 126 个字符', trigger: 'blur' }
            ]
          },
          dsType: {
            rules: [
              { required: true, message: '请选择数据权限' }
            ]
          }
        },
        departTree: [],
        dsType: 0,
        dateScopes: [{
          id: 1,
          des: '全部'
        },
          {
            id: 2,
            des: '本级'
          },
          {
            id: 3,
            des: '本级以及子级'
          },
          {
            id: 4,
            des: '自定义'
          }
        ],
        SHOW_PARENT,
        deptIds: []
      }
    },
    created () {

    },
    methods: {
      loadDeptTreeData () {
        let that = this
        queryDepartTreeList().then((res) => {
          if (res.data) {
            that.departTree = res.data
          }

        })
      },
      add () {
        this.edit({})
      },
      edit (record) {
        this.form.resetFields()
        this.deptIds = []
        this.model= {}
        if (Object.keys(record).length != 0) {
          this.model = Object.assign({}, record)
          for (let i = 0; i < record.roleDepts.length; i++) {
            this.deptIds[i] = record.roleDepts[i]
          }
          this.dsType = record.dsType
          if (this.dsType === 4) {
            this.loadDeptTreeData()
          }
          console.log(this.model)
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model, 'roleName', 'roleDesc', 'roleCode', 'dsType'))
          })
        }
        this.visible = true


      },
      close () {
        this.$emit('close')
        this.dsType = 0
        this.roleDisabled = false
        this.visible = false
      },
      handleOk () {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            const depts = []
            if (this.dsType === 4) {
              for (let i = 0; i < this.deptIds.length; i++) {
                depts.push(
                  this.deptIds[i]
                )
              }
              this.model.roleDepts = depts
            }
            let formData = Object.assign(this.model, values)
            let obj
            if (!this.model.roleId) {
              obj = addRole(formData)
            } else {
              obj = updateRole(formData)
            }
            obj.then((res) => {
              if (res.code === 200) {
                that.$message.success(res.msg)
                that.$emit('ok')
              } else {
                that.$message.warning(res.msg)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      handleChange (value) {
        this.dsType = value
        if (value == 4) {
          this.loadDeptTreeData()
        }
      },
      onChange (value) {
        this.deptIds = value
      }

    }
  }
</script>

<style scoped>

</style>